package servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {


    public static String getAbsoluteResourcePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();  ///D:/IDEA-Git-workspace/2-1/Minicat/target/classes/
        return absolutePath.replaceAll("\\\\","/") + path;
    }

    /**
     * 读取静态资源文件输入流，通过输出流输出
     */
    public static void outputStatcResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        /**
         * 1.先输出流输出响应头
         * 2.输入流写入内容，输出流读取内容
         */

        //确定字节流长度
        int count = 0;
        while(count == 0){
            count = inputStream.available();
        }
        //赋值给资源字节大小
        int resourceSize = count;
        //1.先输出流输出响应头
        outputStream.write(HttpProtocolUtil.getResponseHeader200(resourceSize).getBytes());

        //2.输入流写入内容，输出流读取内容
        long written = 0; //已读取的内容长度
        int byteSize = 1024; // 计划每次缓冲的长度
        byte[] bytes = new byte[byteSize];

        //判断写入的内容是否小于总共的内容
        while(written < resourceSize){
            //resourceSize - written < byteSize  说明剩余读取的大小不足一个1024长度，就按照真实长度进行处理
            if(written + byteSize < resourceSize){
                byteSize =  (int) (resourceSize - written);  //剩余文件长度内容
                bytes = new byte[byteSize];
            }
            //输入流写入内容
            inputStream.read(bytes);
            //输出流读取内容
            outputStream.write(bytes);

            //强制把缓冲区数据输出
            outputStream.flush();
            written += byteSize;
        }

    }

    public static String getWebappResourcePath(String path){
        String webappPath = StaticResourceUtil.class.getResource("/").getPath();  ///D:/IDEA-Git-workspace/2-1/Minicat/target/classes/
        webappPath = webappPath.split(":")[0];
        return webappPath.replaceAll("\\\\","/") +":"+ path;
    }
}
